﻿using System;
using System.Collections.Generic;

namespace UniSender
{
    using Expando = Dictionary<string, object>;
    using IExpando = IDictionary<string, object>;

    public class Analytics
    {
        public virtual string Medium { get; set; }
        public virtual string Source { get; set; }
        public virtual string Campaing { get; set; }
        public virtual string Content { get; set; }
        public virtual string Term { get; set; }
    }

    public class CampaignConfig
    {
        public virtual int MessageId { get; set; }
        public virtual DateTime? StartTime { get; set; }
        public virtual string TimeZone { get; set; }
        public virtual bool? TrackRead { get; set; }
        public virtual bool? TrackLinks { get; set; }
        public virtual string[] Contacts { get; set; }
        public virtual string ContactsUrl { get; set; }
        public virtual bool Defer { get; set; }
        public virtual Analytics Analytics { get; set; }
        public virtual decimal? PaymentLimit { get; set; }
        public virtual Currency? PaymentCurrency { get; set; }

        public CampaignConfig(int messageId)
        {
            Defer = true;
            MessageId = messageId;
        }

        public virtual IExpando Serialize()
        {
            var args = new Expando();

            args["message_id"] = MessageId;
            args["start_time"] = StartTime.Stringify();
            args["timezone"] = TimeZone;
            if (TrackRead != null)
                args["track_read"] = TrackRead.Value ? 1 : 0;
            if (TrackLinks != null)
                args["track_links"] = TrackLinks.Value ? 1 : 0;
            if (Contacts != null && Contacts.Length > 0)
                args["contacts"] = string.Join(",", Contacts);
            args["contacts_url"] = ContactsUrl;
            if (!Defer)
                args["defer"] = 0;
            if (PaymentLimit != null)
            {
                args["payment_limit"] = PaymentLimit.Value.ToString("F", System.Globalization.CultureInfo.InvariantCulture);
                if (PaymentCurrency != null)
                    args["payment_currency"] = PaymentCurrency.Value.ToString();
            }
            if (Analytics != null)
            {
                args["track_ga"] = 1;
                args["ga_medium"] = Analytics.Medium;
                args["ga_source"] = Analytics.Source;
                args["ga_campaign"] = Analytics.Campaing;
                args["ga_content"] = Analytics.Content;
                args["ga_term"] = Analytics.Term;
            }

            return args;
        }
    }
}
